<template>
  <div class="article-detail-page bg-white">
    <div ref="articleRef">
      <ArticleDetail :title="articleData.title" :content="articleData.content" />
    </div>

    <!-- 购药渠道 -->
    <!-- <BuyDrug :data="BuyDrugData" v-if="articleData.switchStatus" /> -->

    <div class="detail-footer van-hairline--top flex flex-justify" v-if="(articleData.prevId || articleData.nextId) && !isPreview">
      <div>
        <div
          class="change-btn"
          v-if="articleData.prevId"
          @click="skip(articleData.prevId, articleData.prevCurrentPage)"
        >
          <span class="iconfont iconchuqu-copy" />
          上一篇
        </div>
      </div>
      <div>
        <div
          class="change-btn"
          v-if="articleData.nextId"
          @click="skip(articleData.nextId, articleData.nextCurrentPage)"
        >
          下一篇
          <span class="iconfont iconjinru" />
        </div>
      </div>
    </div>

    <div class="read-box" v-if="!isPreview">
      <div class="read" @click="onBack">
        确认已读
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, inject } from 'vue';
import { useRouter, useRoute, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
import { CHANNEL, CHANNEL_TEXT } from '@/constants/business';
import Utils from '@/utils/utils';
import { useUserInfo, useRecords } from '@/hooks/store';
import XltData from '@/utils/XltData';
import { useService } from '@/utils/services';
import ArticleDetail from './components/ArticleDetail';

import { useExitPosition, useMediaPoint } from './usePoint';
import { useMediaTime } from './components/useMedia';

export default {
  components: {
    ArticleDetail
  },
  setup() {
    const route = useRoute();
    const router = useRouter();

    const articleRef = ref(null);

    const actions = useService();

    const articleData = ref({});
    const sensors = ref({});
    const articleId = computed(() => route.params.articleId);
    const planDetailId = computed(() => route.query.planDetailId);
    const articleParams = computed(() => route.query);
    const messageId = computed(() => route.query.messageId);
    const isPreview = computed(() => route.query.isPreview);

    // 浏览记录
    let { startRecord } = useRecords(articleId.value);
    let recordTime = null;

    const rootRef = inject('rootRef');
    let isTimeout = false;
    watch(
      () => articleId.value,
      (id) => {
        if (!id) return;
        actions.hos
          .getTrainingArticleInfo({
            ...articleParams.value,
            trainingArticleId: articleId.value,
            openFrom: '培训中心',
            searchTitle: articleParams.value.title || ''
          })
          .then((res) => {
            try {
              res.content = JSON.parse(res.content)[0].content;
            } catch {
              console.log('cuowu');
            }

            articleData.value = res;
            rootRef.value.scrollTop = 0;
            sensors.value = { ...res.sensorsResponse };

            // startRecord(res.trainingArticleId);

            setTimeout(() => {
              startMedia();
            }, 300);

            recordTime = setTimeout(() => {
              isTimeout = true;
            }, 3000);
          });
      },
      {
        immediate: true
      }
    );

    function haveRead() {
      if (planDetailId.value) {
        let planType = route.query.channel == CHANNEL.SMART_PUSH ? 0 : 1;
        actions.hos.haveRead({
          planDetailId: planDetailId.value,
          planType,
          messageId: messageId.value
        });
      }
    }

    let inTime = Utils.date2string(null, '-', true);
    function skip(articleId, currentPage) {
      router.replace(
        `/trainArticle/${articleId}?${Utils.json2params({
          currentPage,
          pageSize: 10,
          ...articleParams.value
        })}`
      );
    }

    const userInfo = useUserInfo();

    const getPosition = useExitPosition({ articleRef, articleData });

    const { resetTime } = useMediaTime();

    const {
      start: startMedia,
      remove: removeMedia,
      reset: resetMedia,
      getPercentage,
      getPlayTime
    } = useMediaPoint();

    function trackData() {
      if (isPreview.value) return;
      let leaveTime = Utils.date2string(null, '-', true);

      // 音视频 播放比例
      let mediaPercentage = getPercentage();

      // 音视频
      if (articleData.value.videoStatus || articleData.value.audioStatus) {
        let mediaTime = getPlayTime();
        // 播放存在  进入时间就是第一次点击播放的时间  否则离开时间就是 进入时间
        if (mediaTime.inTime) {
          inTime = mediaTime.inTime;
          leaveTime = mediaTime.leaveTime || leaveTime;
        } else {
          if (articleData.value.textStatus) {
            if (Utils.dateDiffer(inTime, leaveTime, 60)) {
              leaveTime = Utils.setMinutes(inTime, 60, true);
            }
          } else {
            leaveTime = inTime;
          }
        }
      } else {
        if (articleData.value.textStatus && Utils.dateDiffer(inTime, leaveTime, 60)) {
          leaveTime = Utils.setMinutes(inTime, 60, true);
        }
      }

      sensors.value.openTime = inTime;
      sensors.value.leaveTime = leaveTime;

      sensors.value.searchTitle = route.query.title || '';
      sensors.value.openFrom = CHANNEL_TEXT[route.query.channel];
      sensors.value.departmentId = sensors.value.departmentId || '';
      sensors.value.largeDepartmentId = sensors.value.largeDepartmentId || '';
      sensors.value.branchHospitalId = sensors.value.branchHospitalId || '';
      sensors.value.hospitalId = sensors.value.hospitalId || '';
      sensors.value.outPosition = articleData.value.textStatus ? Number(getPosition()) : 0;
      sensors.value.videoPlayTime = articleData.value.videoStatus
        ? Number(mediaPercentage.video)
        : 0;
      sensors.value.audioPlayTime = articleData.value.audioStatus
        ? Number(mediaPercentage.audio)
        : 0;
      sensors.value.level = sensors.value.level.map((item) => item.toString()) || [];
      sensors.value.patientsId = userInfo.value.patientsId;
      XltData.track('TrainingArticleRead', { ...sensors.value });

      // 发送完毕之后更新时间
      inTime = Utils.date2string(null, '-', true);

      if (isTimeout) {
        haveRead();
        startRecord(articleData.value.trainingArticleId);
        isTimeout = false;
      }
    }

    // 离开时发送数据
    onBeforeRouteLeave(() => {
      // 发送埋点
      trackData();
      // 删除事件
      removeMedia();
      clearTimeout(recordTime);
    });

    // 文章内切换 发送数据
    onBeforeRouteUpdate(() => {
      resetTime();
      // 发送埋点
      trackData();
      // 删除事件
      removeMedia();
      // 初始化埋点数据
      resetMedia();
      clearTimeout(recordTime);
    });

    function onBack() {
      if (route.query.entry) {
        router.push('/home');
      } else {
        router.back();
      }
    }

    return { articleData, skip, articleRef, confirm, onBack, isPreview };
  }
};
</script>

<style lang="scss" scoped>
.article-detail-page {
  min-height: 100%;
  background: #fff;
  padding: 30px 34px 120px;
}

.article-title {
  padding: 30px 0;
  font-size: 44px;
  font-weight: 600;
  color: #373d52;
  line-height: 60px;
}

.article-content {
  font-size: 32px;
  color: #373d52;
}
.detail-footer {
  padding-top: 30px;
  padding-bottom: 30px;
  margin-top: 54px;
  .change-btn {
    font-size: 32px;
    font-weight: 400;
    color: #a2a6b8;
    line-height: 42px;
    & .iconfont {
      font-size: 30px;
    }
  }
}

.read-box {
  position: fixed;
  width: 100%;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20px 34px;
  background: #fff;
  z-index: 10;
}

.read {
  height: 80px;
  background: #27cdc5;
  border-radius: 12px;
  font-size: 28px;
  font-weight: 500;
  color: #ffffff;
  line-height: 80px;
  text-align: center;
}
</style>